package com.ciei.dpagm.handler;

import org.apache.http.HttpStatus;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理类
 * @author fangnuozhou
 * @date 2020/10/28
 */
@Component
public class MyExceptionResolver implements HandlerExceptionResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        try {
            LOGGER.error("捕获全局异常：{}" ,e.toString(),e);
            e.printStackTrace();
            if (e instanceof UnauthorizedException) {
                httpServletResponse.sendError(HttpStatus.SC_FORBIDDEN, "权限不足");
            } else {
                httpServletResponse.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return new ModelAndView();
    }
}
